<script>
  import DepartmentSelect from '$lib/components/common/DepartmentSelect.svelte';
  import { onMount } from 'svelte';
  
  let selectedValues = [];
  let displayIds = []; // 新增：存储显示的ID
  let disabledValues = ['tech-mgmt', 'app-dev'];
  let treeData = [];
  let loading = false;
  
  // 模拟从API获取树形数据
  async function fetchTreeData() {
    loading = true;
    try {
      // 模拟网络延迟
      await new Promise(resolve => setTimeout(resolve, 1000));
      
      // 模拟API返回的数据
      treeData = [
        {
          id: 'bigdata',
          name: '大数据中心',
          children: [
            {
              id: 'tech-mgmt',
              name: '数据科技管理板块',
              children: [
                { id: 'planning', name: '规划推广域' },
                { id: 'architecture', name: '数据架构域' },
                { id: 'other', name: '某某域' }
              ]
            },
            {
              id: 'research',
              name: '数据研发中心',
              children: []
            },
            {
              id: 'app-dev',
              name: '数据应用研发板块',
              children: []
            }
          ]
        }
      ];
    } catch (error) {
      console.error('获取部门数据失败:', error);
      treeData = [];
    } finally {
      loading = false;
    }
  }
  
  // 组件挂载时获取数据
  onMount(() => {
    fetchTreeData();
  });
  
  function handleChange(event) {
    console.log('Selected values changed:', event.detail.selectedValues);
    console.log('Display IDs:', event.detail.displayIds);
    displayIds = event.detail.displayIds || [];
  }
  
  function clearAll() {
    selectedValues = [];
  }
  
  function selectAll() {
    selectedValues = ['planning', 'architecture', 'other', 'research', 'app-dev'];
  }
  
  function selectParent() {
    selectedValues = ['bigdata'];
  }
  
  function selectTechMgmt() {
    selectedValues = ['tech-mgmt'];
  }
  
  function selectPartialChildren() {
    selectedValues = ['planning', 'architecture'];
  }
  
  function selectMixed() {
    selectedValues = ['planning', 'research'];
  }
  
  function refreshData() {
    fetchTreeData();
  }
  
  function selectFirstLevel() {
    // 选择一级节点（根节点）
    selectedValues = ['bigdata'];
  }
  
  // 获取节点路径用于显示
  function getNodePath(nodeId) {
    const paths = {
      'bigdata': '大数据中心',
      'tech-mgmt': '大数据中心/数据科技管理板块',
      'planning': '大数据中心/数据科技管理板块/规划推广域',
      'architecture': '大数据中心/数据科技管理板块/数据架构域',
      'other': '大数据中心/数据科技管理板块/某某域',
      'research': '大数据中心/数据研发中心',
      'app-dev': '大数据中心/数据应用研发板块'
    };
    return paths[nodeId] || nodeId;
  }
</script>

<svelte:head>
  <title>部门选择器测试</title>
</svelte:head>

<div class="test-page">
  <h1>部门选择器测试页面</h1>
  
  <div class="test-section">
    <h2>基本功能测试</h2>
    <div class="test-item">
      <h3>正常状态</h3>
      {#if loading}
        <div class="loading-state">
          <span>🔄 正在加载部门数据...</span>
        </div>
      {:else}
        <DepartmentSelect 
          bind:selectedValues 
          bind:treeData
          on:change={handleChange}
          placeholder="请选择部门..."
        />
      {/if}
      
      <div class="selected-info">
        <strong>已选择的ID：</strong>
        {#if selectedValues.length > 0}
          <pre>{JSON.stringify(selectedValues, null, 2)}</pre>
        {:else}
          <span class="empty">未选择任何部门</span>
        {/if}
        
        <strong>显示的ID（去重后）：</strong>
        {#if displayIds.length > 0}
          <pre>{JSON.stringify(displayIds, null, 2)}</pre>
        {:else}
          <span class="empty">无显示ID</span>
        {/if}
        
        <strong>对应路径：</strong>
        {#if displayIds.length > 0}
          <ul class="path-list">
            {#each displayIds as id}
              <li>{getNodePath(id)}</li>
            {/each}
          </ul>
        {:else}
          <span class="empty">无</span>
        {/if}
      </div>
    </div>
    
    <div class="test-item">
      <h3>禁用状态</h3>
      <DepartmentSelect 
        selectedValues={disabledValues}
        treeData={treeData}
        disabled={true}
        placeholder="禁用状态"
      />
      <div class="selected-info">
        <strong>预设选中：</strong>
        <ul class="path-list">
          {#each disabledValues as id}
            <li>{getNodePath(id)}</li>
          {/each}
        </ul>
      </div>
    </div>
  </div>
  
  <div class="test-section">
    <h2>快捷操作按钮</h2>
    <div class="button-group">
      <button class="btn btn-info" on:click={refreshData}>
        🔄 重新加载数据
      </button>
      <button class="btn btn-primary" on:click={clearAll}>
        清空选择
      </button>
      <button class="btn btn-secondary" on:click={selectFirstLevel}>
        选择一级节点
      </button>
      <button class="btn btn-secondary" on:click={selectAll}>
        选择所有叶子节点
      </button>
      <button class="btn btn-secondary" on:click={selectParent}>
        选择根节点
      </button>
      <button class="btn btn-secondary" on:click={selectTechMgmt}>
        选择管理板块
      </button>
      <button class="btn btn-secondary" on:click={selectPartialChildren}>
        部分选择子节点
      </button>
      <button class="btn btn-secondary" on:click={selectMixed}>
        混合选择
      </button>
    </div>
  </div>
  
  <div class="test-section">
    <h2>测试场景说明</h2>
    <div class="scenario-list">
      <div class="scenario-item">
        <h4>🎯 父子联动测试</h4>
        <p>点击"选择管理板块"，观察是否自动选中所有子节点，标签是否合并显示</p>
      </div>
      
      <div class="scenario-item">
        <h4>🎯 半选状态测试</h4>
        <p>点击"部分选择子节点"，观察父节点是否显示半选状态（横线图标）</p>
      </div>
      
      <div class="scenario-item">
        <h4>🎯 智能合并测试</h4>
        <p>手动选中"规划推广域"和"数据架构域"和"某某域"，观察是否自动合并为父节点</p>
      </div>
      
      <div class="scenario-item">
        <h4>🎯 标签删除测试</h4>
        <p>在已选择的标签上点击 × 按钮，观察是否正确删除节点及其子节点</p>
      </div>
      
      <div class="scenario-item">
        <h4>🎯 展开折叠测试</h4>
        <p>点击树节点前的箭头图标，观察展开/折叠动画效果</p>
      </div>
    </div>
  </div>
  
  <div class="test-section">
    <h2>功能特性</h2>
    <div class="feature-list">
      <div class="feature-item">
        <h4>✅ ID存储，路径显示</h4>
        <p>内部使用节点ID存储选择状态，界面显示完整路径</p>
      </div>
      
      <div class="feature-item">
        <h4>✅ 智能父子联动</h4>
        <p>选中父节点自动选中所有子节点，所有子节点选中时自动选中父节点</p>
      </div>
      
      <div class="feature-item">
        <h4>✅ 三态复选框</h4>
        <p>支持未选中、半选中、全选中三种状态，视觉反馈清晰</p>
      </div>
      
      <div class="feature-item">
        <h4>✅ 标签智能合并</h4>
        <p>当父节点被选中时，只显示父节点标签，避免冗余显示</p>
      </div>
      
      <div class="feature-item">
        <h4>✅ 响应式设计</h4>
        <p>支持不同屏幕尺寸，标签自动换行，内容溢出处理</p>
      </div>
      
      <div class="feature-item">
        <h4>✅ 键盘友好</h4>
        <p>支持Tab键导航，空格键选择，Esc键关闭下拉</p>
      </div>
    </div>
  </div>
  
  <div class="test-section">
    <h2>数据结构示例</h2>
    <div class="code-block">
      <h4>树形数据：</h4>
      <pre><code>{JSON.stringify([
        {
          id: 'bigdata',
          name: '大数据中心',
          children: [
            {
              id: 'tech-mgmt',
              name: '数据科技管理板块',
              children: [
                { id: 'planning', name: '规划推广域' },
                { id: 'architecture', name: '数据架构域' },
                { id: 'other', name: '某某域' }
              ]
            },
            { id: 'research', name: '数据研发中心', children: [] },
            { id: 'app-dev', name: '数据应用研发板块', children: [] }
          ]
        }
      ], null, 2)}</code></pre>
    </div>
  </div>
  
  <div class="test-section">
    <h2>API数据模拟</h2>
    <div class="feature-list">
      <div class="feature-item">
        <h4>📡 异步数据加载</h4>
        <p>模拟从后端API获取部门树形数据，支持加载状态显示</p>
      </div>
      
      <div class="feature-item">
        <h4>🔄 数据刷新</h4>
        <p>支持重新获取数据，适用于数据更新场景</p>
      </div>
      
      <div class="feature-item">
        <h4>⚠️ 错误处理</h4>
        <p>处理网络错误和数据格式异常情况</p>
      </div>
      
      <div class="feature-item">
        <h4>💾 状态管理</h4>
        <p>已选择状态在数据重新加载时保持不变</p>
      </div>
    </div>
  </div>
</div>

<style>
  .test-page {
    max-width: 800px;
    margin: 0 auto;
    padding: 20px;
    font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, sans-serif;
  }
  
  h1 {
    color: #24292f;
    border-bottom: 1px solid #d0d7de;
    padding-bottom: 10px;
    margin-bottom: 30px;
  }
  
  .test-section {
    margin-bottom: 40px;
    padding: 20px;
    border: 1px solid #d0d7de;
    border-radius: 8px;
    background: #f6f8fa;
  }
  
  .test-item {
    margin-bottom: 20px;
    padding: 15px;
    background: white;
    border-radius: 6px;
    border: 1px solid #d0d7de;
  }
  
  .test-item h3 {
    margin: 0 0 15px 0;
    color: #24292f;
  }
  
  .selected-info {
    margin-top: 15px;
    padding: 10px;
    background: #f8f9fa;
    border-radius: 4px;
    border: 1px solid #e9ecef;
  }
  
  .selected-info pre {
    margin: 5px 0 0 0;
    font-size: 12px;
    color: #24292f;
  }
  
  .empty {
    color: #656d76;
    font-style: italic;
  }
  
  .button-group {
    display: flex;
    gap: 10px;
    flex-wrap: wrap;
  }
  
  .btn {
    padding: 8px 16px;
    border: 1px solid #d0d7de;
    border-radius: 6px;
    background: white;
    color: #24292f;
    cursor: pointer;
    font-size: 14px;
    transition: all 0.2s;
  }
  
  .btn:hover {
    background: #f3f4f6;
  }
  
  .btn-primary {
    background: #0969da;
    color: white;
    border-color: #0969da;
  }
  
  .btn-primary:hover {
    background: #0860ca;
  }
  
  .btn-secondary {
    background: #f6f8fa;
  }
  
  .btn-info {
    background: #17a2b8;
    color: white;
    border-color: #17a2b8;
  }
  
  .btn-info:hover {
    background: #138496;
  }
  
  .path-list {
    margin: 5px 0 0 0;
    padding-left: 20px;
    font-size: 12px;
    color: #24292f;
  }
  
  .scenario-list {
    display: grid;
    gap: 15px;
  }
  
  .scenario-item {
    padding: 15px;
    background: white;
    border-radius: 6px;
    border: 1px solid #d0d7de;
    border-left: 4px solid #0969da;
  }
  
  .scenario-item h4 {
    margin: 0 0 8px 0;
    color: #0969da;
  }
  
  .scenario-item p {
    margin: 0;
    color: #656d76;
    font-size: 14px;
  }
  
  .code-block {
    background: white;
    border-radius: 6px;
    border: 1px solid #d0d7de;
    padding: 15px;
  }
  
  .code-block h4 {
    margin: 0 0 10px 0;
    color: #24292f;
  }
  
  .code-block pre {
    margin: 0;
    padding: 10px;
    background: #f6f8fa;
    border-radius: 4px;
    overflow-x: auto;
    font-size: 11px;
    color: #24292f;
  }
  
  .loading-state {
    padding: 20px;
    text-align: center;
    color: #656d76;
    background: #f6f8fa;
    border: 1px solid #d0d7de;
    border-radius: 6px;
  }
</style>
